package com.ctbri.JWLetter.frame;

import javax.annotation.Resource;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.elasticsearch.client.transport.TransportClient;
import org.springframework.stereotype.Component;

/**
 * ES数据层切面类
 * 
 * @author Hogan
 *
 */
@Aspect
@Component("eSDataAspect")
public class ESDataAspect {

	@Resource
	private ESDataPooledConnection eSDataPooledConnection;

	/**
	 * 执行方法前获取ES连接
	 * 
	 * @param jp
	 * @throws Exception
	 */
	@Before("within(com.ctbri.JWLetter.dao.es.impl..*)")
	public void obtainClient(JoinPoint jp) throws Exception {
		Object[] args = jp.getArgs();
		if (args != null && args.length > 0) {
			if (args[0] instanceof TransportClient) {
				args[0] = eSDataPooledConnection.getCurrentConnecton();
			}
		}
	}

	/**
	 * 执行方法后释放ES连接
	 * 
	 * @param jp
	 * @throws Exception
	 */
	@After("within(com.ctbri.JWLetter.dao.es.impl..*)")
	public void release(JoinPoint jp) throws Exception {
		Object[] args = jp.getArgs();
		if (args != null && args.length > 0) {
			if (args[0] instanceof TransportClient) {
				eSDataPooledConnection.releaseConn((TransportClient) args[0]);
			}
		}
	}

}
